package com.study.common.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 时间工具类
 *
 * @author study
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

    public static final String YYYY = "yyyy";

    public static final String YYYY_MM = "yyyy-MM";

    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final String[] PARSE_PATTERNS = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    public static Long utcLong() {
        return Instant.now().toEpochMilli();
    }

    public static Date utcDate() {
        return new Date();
    }

    public static LocalDateTime utcLocalDateTime() {
        return LocalDateTime.now(ZoneOffset.UTC);
    }

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static String dateTimeNow(final String format) {
        return parseDateToStr(format, DateUtils.utcDate());
    }

    public static String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static String convertToTimeZoneString(Date date, String timeZoneId) {
        // 使用源时区创建ZonedDateTime对象
        ZonedDateTime sourceDateTime = date.toInstant().atZone(ZoneOffset.UTC);
        // 将时区转换为目标时区
        ZonedDateTime targetDateTime = sourceDateTime.withZoneSameInstant(ZoneId.of(timeZoneId));
        return targetDateTime.format(FORMATTER);
    }

    public static String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static String datePath() {
        Date now = DateUtils.utcDate();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static String dateTime() {
        Date now = DateUtils.utcDate();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), PARSE_PATTERNS);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }
    /**
     * 计算两个时间的时分秒
     */
    public static String getDateHMS(LocalDateTime startDate, LocalDateTime endDate) {

        // 计算两个时间点之间的时间间隔
        Duration duration = Duration.between(startDate, endDate);

        // 获取时间间隔的分钟数
        long hours = duration.toHours();
        long minutes = duration.toMinutes() % 60; // 使用取模运算符获取剩余的分钟数
        long seconds = duration.getSeconds() % 60; // 使用取模运算符获取剩余的秒数
        return hours + "H:" + minutes + "min:" + seconds + "s";
    }
    /**
     * 根据秒数计算小时数
     */
    public static Double getHours(Long mills) {
        return mills / 3600.0;
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }


    /**
     * Timestamp 转 UTC LocalDateTime
     *
     * @param timestamp
     * @return LocalDateTime
     * @Title: getDateTimeOfTimestamp_not1000
     * @Description: TODO
     * @author: 许智皓
     * @date: 2021年5月26日 上午9:30:37
     * @version: V1.0
     * @updateDate:
     * @update:
     */
    public static LocalDateTime getDateTimeOfTimestamp_not1000(long timestamp) {

        return Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.UTC).toLocalDateTime();
    }


    /**
     * 时间戳转换成日期格式字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param timeStamp
     * @return
     */
    public static String timeStampToDateStr(long timeStamp) {

        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return sdf.format(new Date(timeStamp));
    }


    public static LocalDateTime aslocalDateTimeUTC() {

        return LocalDateTime.now(ZoneOffset.UTC);
    }


    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {

        return Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.UTC).toLocalDateTime();
    }

    public static String convertDateToString(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    public static Date asDate(LocalDateTime localDateTime) {

        // return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        return Date.from(localDateTime.atZone(ZoneOffset.UTC).toInstant());
    }


    public static long localToTimestampMilli(LocalDateTime localDate) {

        if (null == localDate) {
            return 0;
        }

        return localDate.toInstant(ZoneOffset.UTC).toEpochMilli(); //转为UTC时间发出来

    }


    /**
     * LocalDateTime计算时间差 返回秒
     *
     * @param time1
     * @param time2
     * @return long
     * @Title: localDateTimeBetweenTos
     * @Description: TODO
     * @author: 许智皓
     * @date: 2021年10月27日 上午11:33:49
     * @Company: Magicyo.平台产品部
     * @version: V1.0
     * @updateDate:
     * @update:
     */
    public static long localDateTimeBetweenTos(LocalDateTime time1, LocalDateTime time2) {

        if (null != time1 && null != time2) {

            return Duration.between(time2, time1).toMillis() / 1000;
        }

        return 0;
    }

    public static Date convertDateToDate(Date date, String formatString) {
        if (null == date || org.apache.commons.lang3.StringUtils.isBlank(formatString)) {
            return null;
        }
        try {
            return new SimpleDateFormat(formatString).parse(convertDateToString(date, formatString));
        } catch (Exception e) {
            return null;
        }
    }

    public static Date timeStampToDate(long timeStamp) {
        return convertDateToDate(new Date(timeStamp), YYYY_MM_DD_HH_MM_SS);
    }

    public static LocalDate getLocalDateUtc() {

        return LocalDate.now(ZoneOffset.UTC);

    }

    public static long getTimeMillis() {

        return System.currentTimeMillis() / 1000;
    }

    /**
     * LocalDateTime时间转成UTC时间截,秒
     * @Title: localToTimestamp
     * @Description: TODO
     * @author: 许智皓
     * @date: 2021年5月25日 下午3:43:46
     * @version: V1.0
     * @param localDate
     * @return long
     *
     * @updateDate:
     * @update:
     */
    public static long localToTimestamp(LocalDateTime localDate) {

        //LocalDateTime localDateTime = LocalDateTime.parse("2021-05-25 01:48:50", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //return localDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() / 1000;(转为本地时间发出来)

        if(null == localDate) {
            return 0;
        }

        return localDate.toInstant(ZoneOffset.UTC).toEpochMilli() / 1000; //转为UTC时间发出来

    }
    public static String localDateTimeToStr() {

        return DateUtils.convertDateToString(DateUtils.asDate(DateUtils.aslocalDateTimeUTC()), DateUtils.YYYY_MM_DD_HH_MM_SS);
    }

    public static String localDateTimeToStr(LocalDateTime time) {

        return DateUtils.convertDateToString(DateUtils.asDate(time), DateUtils.YYYY_MM_DD_HH_MM_SS);
    }
}
